package com.example.testapp.ui.balance

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.testapp.R
import com.example.testapp.domain.util.ImageStorageUtil
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.io.File
import java.util.concurrent.ExecutionException

/**
 * 相机拍照Fragment
 */
class CameraFragment : Fragment() {
    
    companion object {
        private const val REQUEST_CODE_PERMISSIONS = 10
        private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)
    }
    
    private lateinit var viewFinder: PreviewView
    private lateinit var captureButton: FloatingActionButton
    private lateinit var loadingView: View
    
    private var imageCapture: ImageCapture? = null
    private lateinit var viewModel: BalanceViewModel
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_camera, container, false)
        
        // 初始化视图
        viewFinder = rootView.findViewById(R.id.viewFinder)
        captureButton = rootView.findViewById(R.id.cameraCaptureButton)
        loadingView = rootView.findViewById(R.id.loadingView)
        
        return rootView
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 初始化ViewModel
        viewModel = ViewModelProvider(requireActivity())[BalanceViewModel::class.java]
        
        // 观察加载状态
        viewModel.operationState.observe(viewLifecycleOwner) { state ->
            val isProcessing = state is BalanceViewModel.OperationState.Loading
            loadingView.visibility = if (isProcessing) View.VISIBLE else View.GONE
            captureButton.isEnabled = !isProcessing
        }
        
        // 设置拍照按钮点击事件
        captureButton.setOnClickListener {
            takePhoto()
        }
        
        // 检查并请求相机权限
        if (allPermissionsGranted()) {
            startCamera()
        } else {
            requestPermissions(REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
        }
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (allPermissionsGranted()) {
                startCamera()
            } else {
                Toast.makeText(requireContext(), "需要相机权限", Toast.LENGTH_SHORT).show()
                requireActivity().onBackPressed()
            }
        }
    }
    
    /**
     * 检查所有权限是否已授权
     */
    private fun allPermissionsGranted(): Boolean {
        return REQUIRED_PERMISSIONS.all {
            ContextCompat.checkSelfPermission(requireContext(), it) == PackageManager.PERMISSION_GRANTED
        }
    }
    
    /**
     * 启动相机
     */
    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
        
        cameraProviderFuture.addListener({
            try {
                // 绑定相机生命周期
                val cameraProvider = cameraProviderFuture.get()
                
                // 预览配置
                val preview = Preview.Builder().build()
                preview.setSurfaceProvider(viewFinder.surfaceProvider)
                
                // 图片拍摄配置
                imageCapture = ImageCapture.Builder()
                    .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                    .build()
                
                // 选择后置摄像头
                val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
                
                // 解绑之前的用例并绑定新的用例
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(
                    viewLifecycleOwner,
                    cameraSelector,
                    preview,
                    imageCapture
                )
                
            } catch (e: ExecutionException) {
                // 处理异常
                Toast.makeText(requireContext(), "启动相机失败: ${e.message}", Toast.LENGTH_SHORT).show()
            } catch (e: InterruptedException) {
                Toast.makeText(requireContext(), "启动相机失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }, ContextCompat.getMainExecutor(requireContext()))
    }
    
    /**
     * 拍照
     */
    private fun takePhoto() {
        val imageCapture = imageCapture ?: return
        
        try {
            // 创建临时文件
            val photoFile = ImageStorageUtil.createTempImageFile(requireContext())
            
            // 输出选项
            val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
            
            // 拍照
            imageCapture.takePicture(
                outputOptions,
                ContextCompat.getMainExecutor(requireContext()),
                object : ImageCapture.OnImageSavedCallback {
                    override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                        // 图片保存成功
                        val savedUri = Uri.fromFile(photoFile)
                        processCapturedImage(savedUri)
                    }
                    
                    override fun onError(exception: ImageCaptureException) {
                        // 图片保存失败
                        Toast.makeText(
                            requireContext(),
                            "拍照失败: ${exception.message}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            )
        } catch (e: Exception) {
            Toast.makeText(requireContext(), "拍照出错: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 处理拍摄的图片
     * @param imageUri 图片URI
     */
    private fun processCapturedImage(imageUri: Uri) {
        try {
            // 获取文件并处理图片
            val photoFile = File(imageUri.path ?: "")
            if (photoFile.exists()) {
                viewModel.processImage(photoFile)
            } else {
                Toast.makeText(requireContext(), "无法找到图片文件", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(requireContext(), "处理图片失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
} 